var express = require('express');
var connection = require('../db/db_utill');

var router = express.Router();

router.post('/register', function (req, res) {
  //获取表单post数据
  var body = req.body

  connection.query(`select * from user_info where username = ?`, [body.username], function (error, results, fields) {
    if (error) {
      throw error;
    }
    else if (results.length) {
      var string = JSON.stringify(results);
      var user_info = JSON.parse(string)[0];
      if (body.username == user_info.username) {
        return res.json({
          status: 400,
          message: '用户名已存在'
        })
      } else {
        connection.query('INSERT INTO user_info value(?,?,?,?,?,?,?)', [null, body.username, body.password, 'http://127.0.0.1:3000/public/uploads/default.jpg', null, null, null], function (error, results, fields) {
          if (error) {
            throw error;
          } else {
            //将登陆信息保存在session中
            req.session.user = user_info
            // 服务端重定向针对异步请求无效
            return res.json({
              //用户数据
              user: req.session.user,
              message: '注册成功！',
              status: 200
            })
          }
        });
      }
    }
  })
})

module.exports = router;